import Footer from '@/components/Footer';
import { Link, useParams } from '@@/exports';
import {
  LinkOutlined,
  LockOutlined,
  MailOutlined,
  RedditOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { LoginForm, ProFormCheckbox, ProFormText } from '@ant-design/pro-components';
import { ProFormCaptcha } from '@ant-design/pro-form';
import { Helmet, history } from '@umijs/max';
import { Form, message, Tabs } from 'antd';
import React, { useEffect, useState } from 'react';
import Settings from '../../../../config/defaultSettings';
import { userRegisterUsingPost } from '@/services/Kapi-backend/userController';

const Register: React.FC = () => {
  const [type, setType] = useState<string>('email');
  const [invitationCode, setInvitationCode] = useState<string>('');
  const [form] = Form.useForm();
  const params = useParams();

  useEffect(() => {
    if (params.id) {
      setInvitationCode(params.id);
      form.setFieldsValue({ invitationCode: params.id }); // 修复字段设置
    }
  }, [params.id]);

  useEffect(() => {
    form.setFieldsValue({ invitationCode });
  }, [invitationCode]);

  const doRegister = (res: any) => {
    if (res.data && res.code === 0) {
      message.success('注册成功');
      setTimeout(() => {
        history.push('/user/login');
      }, 100);
    } else {
      // 如果 code 不等于 0，刷新页面
      window.location.reload();
    }
  };

  const handleSubmit = async (values: API.UserRegisterRequest) => {
    try {
      // 注册
      const res = await userRegisterUsingPost({
        ...values,
      });
      doRegister(res);
    } catch (error) {
      const defaultLoginFailureMessage = '注册失败，请重试！';
      message.error(defaultLoginFailureMessage);
    }
  };

  // 内联样式
  const containerStyle = {
    display: 'flex',
    flexDirection: 'column',
    height: '100vh',
    overflow: 'auto',
    backgroundImage: 'linear-gradient(to top, #accbee 0%, #e7f0fd 100%)',
    backgroundSize: '100% 100%',
  };

  const formContainerStyle = {
    flex: 1,
    padding: '43px 0 0 0',
  };

  const logoStyle = {
    marginBottom: 20,
    textAlign: 'center',
  };

  const linkStyle = {
    float: 'right',
    marginTop: -18,
    color: '#1890ff',
    cursor: 'pointer',
  };

  return (
    <div style={containerStyle}>
      <Helmet>
        <title>{'注册'} - {Settings.title}</title>
      </Helmet>
      <div style={formContainerStyle}>
        <LoginForm
          form={form}
          submitter={{
            searchConfig: {
              submitText: '注册',
            },
          }}
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          title={
            <div style={logoStyle}>
              <img src="/assets/logo_title.png" width={320} alt="logo" />
            </div>
          }
          initialValues={{
            invitationCode: invitationCode,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.UserRegisterRequest);
          }}
        >
          <Tabs
            centered
            items={[
              {
                key: 'account',
                label: '平台账号注册',
              },
            ]}
          />
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: <RedditOutlined />,
              }}
              placeholder={'用户昵称'}
            />
            <ProFormText
              name="userAccount"
              fieldProps={{
                size: 'large',
                prefix: <UserOutlined />,
              }}
              placeholder={'账号'}
              rules={[
                {
                  required: true,
                  message: '❗账号不能为空',
                },
              ]}
            />
            <ProFormText.Password
              name="userPassword"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder={'密码'}
              rules={[
                {
                  required: true,
                  message: '❗密码不能为空',
                },
              ]}
            />
            <ProFormText.Password
              name="checkPassword"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder={'确认密码'}
              rules={[
                {
                  required: true,
                  message: '❗确认密码不能为空',
                },
              ]}
            />
          </>

          <ProFormCheckbox
            initialValue={true}
            name="agreeToAnAgreement"
            rules={[
              () => ({
                validator(_, value) {
                  if (!value) {
                    return Promise.reject(new Error('请阅读并同意平台协议'));
                  }
                  return Promise.resolve();
                },
                required: true,
              }),
            ]}
          >
            已阅读并同意：
            <a href={'javascript:void(0);'} rel="noreferrer">
              隐私协议、
            </a>
            <a href={'javascript:void(0);'} rel="noreferrer">
              用户协议
            </a>
          </ProFormCheckbox>
          <div>
            <Link to={'/user/login'} style={linkStyle}>
              <p>已有账号？点击前往登录</p>
            </Link>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Register;
